package pers.wk.queues.direct;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import pers.wk.config.MQConfig;
import pers.wk.utils.MQConnectionUtils;

/**
 * 消息发布确认机制-amqp事务
 */
public class TransactionProducer {

    public static void main(String[] args) {
        //1.ConnectionFactory
        ConnectionFactory connectionFactory = MQConnectionUtils.getConnectionFactory("/");
        Connection connection = null;
        Channel channel = null;
        try {
            //2.创建连接
            connection = connectionFactory.newConnection();
            //3.通过连接获取通道Channel
            channel = connection.createChannel();
            //创建交换机
            channel.exchangeDeclare(MQConfig.ExchangeName.DIRECT_EXCHANGE, MQConfig.ExchangeType.direct);
            System.out.println("路由模式模式direct-生产者启动。。。");

            String routingKey = "email";
            String msg = "hello world";

            // 将当前信道设置成事务模式
            channel.txSelect();
            try {
                //sms email
                channel.basicPublish(MQConfig.ExchangeName.DIRECT_EXCHANGE, routingKey, null, msg.getBytes());
                System.out.println(msg);
                int i = 1/0;
                // 提交事务
                channel.txCommit();
            } catch (Exception e) {
                e.printStackTrace();
                // 回滚事务
                channel.txRollback();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MQConnectionUtils.close(connection, channel);
        }
    }
}
